package stancel.peter.smartsilencer.background;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import stancel.peter.smartsilencer.Event;
import stancel.peter.smartsilencer.SmartSilencer;
import stancel.peter.smartsilencer.TimeAlarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * Sluzi na vytvorenie alarmu, ktory spusta CheckingService.
 * @author Peter Stancel
 */
public class AlarmService extends Service {

	private SmartSilencer smartSilencer;
	private List<Event> list;
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		smartSilencer = (SmartSilencer) getApplication();
		list = smartSilencer.loadFromFile();
	}
	
	/**
	 * Vytvori opakovany alarm.
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
//		List<Event> list = smartSilencer.loadFromFile();

		if (!list.isEmpty()) {
			List<TimeAlarm> timeAlarmList = refreshTimeAlarmList();
			Log.i("AlarmService", "pocet: " + timeAlarmList.size());
			if (!timeAlarmList.isEmpty()) {
				Collections.sort(timeAlarmList);
				TimeAlarm timeAlarm = getTimeAlarm(list, timeAlarmList);
				if (timeAlarm != null) {
//					System.out.println("cas: " + timeAlarm.getDate().getTime().toGMTString());
					Intent checkingService = new Intent(this, CheckingService.class);
					AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
					PendingIntent sender = PendingIntent.getService(this, 66311, checkingService,
							PendingIntent.FLAG_UPDATE_CURRENT);

					alarmManager.set(AlarmManager.RTC_WAKEUP, timeAlarm.getDate().getTimeInMillis(), sender);

					if (!timeAlarm.isOneTime()) {
						Calendar start = (Calendar) timeAlarm.getDate().clone();
						start.add(Calendar.DATE, 7);
						timeAlarmList.add(new TimeAlarm(start, timeAlarm.getName(), timeAlarm.isOneTime()));
					}
					timeAlarmList.remove(timeAlarm);
					smartSilencer.saveDatesListToFile(timeAlarmList);
					System.out.println("pocet2: " + timeAlarmList.size());
				}
			}
		}
		stopSelf();
		return START_STICKY;
	}

	private List<TimeAlarm> refreshTimeAlarmList(){
		List<TimeAlarm> timeAlarmList = new ArrayList<TimeAlarm>();
		
		Calendar calendar = Calendar.getInstance();
		int day = calendar.get(Calendar.DAY_OF_WEEK) - 1;

//		List<Event> list = smartSilencer.loadFromFile();
		if (!list.isEmpty()) {
			for (Event event : list) {
				boolean[] days = event.getDays();
				String name = event.getName();
				boolean onetime = event.isOnetime();
				for (int i = 0; i < 7; i++) {
					if (days[i]) {
						Calendar start = Calendar.getInstance();		//new Date(event.getDateStart().getTimeInMillis());
						start.set(Calendar.HOUR_OF_DAY, event.getDateStart() / 100);
						start.set(Calendar.MINUTE, event.getDateStart() % 100);
						Calendar end = Calendar.getInstance();		//new Date(event.getDateEnd().getTimeInMillis());
						end.set(Calendar.HOUR_OF_DAY, event.getDateEnd() / 100);
						end.set(Calendar.MINUTE, event.getDateEnd() % 100);
						
						int number = (7 - day + i) % 7;
						start.add(Calendar.DATE, number);
						end.add(Calendar.DATE, number);
						
						Calendar now = Calendar.getInstance();
						while (start.getTimeInMillis() <= now.getTimeInMillis()) {
							start.add(Calendar.DATE, 7);
						}
						while (end.getTimeInMillis() <= now.getTimeInMillis()) {
							end.add(Calendar.DATE, 7);
						}
						timeAlarmList.add(new TimeAlarm(start, name, onetime));
						timeAlarmList.add(new TimeAlarm(end, name, onetime));
					}
				}
			}
		}
		timeAlarmList = removeOldAlarms(timeAlarmList);
//		smartSilencer.saveDatesListToFile(timeAlarmList);
		return timeAlarmList;
	}
	
	/**
	 * Remove old TileAlarms which have OneTime = true.
	 * @param timeAlarmList
	 * @return
	 */
	private List<TimeAlarm> removeOldAlarms(List<TimeAlarm> timeAlarmList) {
		if(!timeAlarmList.isEmpty()){
			Iterator<TimeAlarm> iterator = timeAlarmList.iterator();
			while (iterator.hasNext()) {
				TimeAlarm timeAlarm = iterator.next();
				if (timeAlarm.isOneTime()) {
					Date date = new Date();
					if (timeAlarm.getDate().getTimeInMillis() <= date.getTime()) {
						iterator.remove();
					}
				}
			}
		}
		return timeAlarmList;
	}

	private TimeAlarm getTimeAlarm(List<Event> list, List<TimeAlarm> timeAlarmList) {
		for (TimeAlarm timeAlarm : timeAlarmList) {
			for (Event event : list) {
				if (event.isTurnOn() && event.getName().equals(timeAlarm.getName())) {
//					Log.i("AlarmService", "TENTO:  "+ timeAlarm.getDate().getTime().toGMTString());
					return timeAlarm;
				}
			}
		}
		return null;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}
